package com.anji.aj_flutter_appsp_push;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.NonNull;

import com.anji.plus.ajpushlibrary.AppSpPushConfig;
import com.anji.plus.ajpushlibrary.AppSpPushLog;
import com.anji.plus.ajpushlibrary.AppSpPushConstant;
import com.anji.plus.ajpushlibrary.base.ActionType;
import com.anji.plus.ajpushlibrary.base.BrandType;
import com.anji.plus.ajpushlibrary.http.AppSpPushRequestUrl;
import com.anji.plus.ajpushlibrary.model.NotificationMessageModel;
import com.anji.plus.ajpushlibrary.util.BrandUtil;
import com.anji.plus.ajpushlibrary.util.PhoneUtil;
import com.google.gson.Gson;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/**
 * Copyright © 2018 anji-plus
 * 安吉加加信息技术有限公司
 * http://www.anji-plus.com
 * All rights reserved.
 * <p>
 * Appsp-Push 插件
 * </p>
 */
public class AjFlutterAppspPushPlugin implements FlutterPlugin, MethodCallHandler {
    private MessageReceiver mMessageReceiver;
    private NotificationMessageModel notificationMessageModel;
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel channel;
    private FlutterPluginBinding binding;
    private Context mContext;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "aj_flutter_appsp_push");
        channel.setMethodCallHandler(this);
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(AppSpPushConstant.MESSAGE_RECEIVED_ACTION);
        flutterPluginBinding.getApplicationContext().registerReceiver(mMessageReceiver, filter);
        binding = flutterPluginBinding;
        mContext = binding.getApplicationContext();
        initConfiguration();
        debugConfiguration();
    }

    //通知flutter，处理路由 TODO
    private void notifyFlutterRoute() {

    }

    //对于小米，点击通知跳转到主页，对于Flutter，先跳到主页，再考虑路由
    private void snapToMainActivity() {
        Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName());
        mContext.startActivity(intent);
    }

    ///从build.gradle读取配置
    private void initConfiguration() {
        AppSpPushLog.d("AjFlutterAppspPushPlugin initConfiguration ");
        try {
            ApplicationInfo appInfo = mContext.getPackageManager().getApplicationInfo(mContext.getPackageName(),
                    PackageManager.GET_META_DATA);
            AppSpPushConstant.packageName = mContext.getPackageName();
            AppSpPushRequestUrl.Host = AppSpPushConstant.appspHost = getMetaInfoByKey(appInfo, "appspHost");
            AppSpPushConstant.appspAppKey = getMetaInfoByKey(appInfo, "appspAppKey");
            AppSpPushConstant.appspSecretKey = getMetaInfoByKey(appInfo, "appspSecretKey");
            AppSpPushConstant.oppoAppKey = getMetaInfoByKey(appInfo, "oppoAppKey");
            AppSpPushConstant.oppoAppSecret = getMetaInfoByKey(appInfo, "oppoAppSecret");
            AppSpPushConstant.xmAppId = getMetaInfoByKey(appInfo, "xmAppId");
            AppSpPushConstant.xmAppKey = getMetaInfoByKey(appInfo, "xmAppKey");
        } catch (Exception e) {

        }
        AppSpPushConfig.getInstance().init(mContext, AppSpPushConstant.appspAppKey, AppSpPushConstant.appspSecretKey, AppSpPushRequestUrl.Host + AppSpPushRequestUrl.putPushInfo);
    }

    private void debugConfiguration() {
        AppSpPushLog.d(" AppSpPushRequestUrl.Host " + AppSpPushRequestUrl.Host);
        AppSpPushLog.d(" AppSpPushConstant.packageName " + AppSpPushConstant.packageName);
        AppSpPushLog.d(" AppSpPushConstant.appspAppKey " + AppSpPushConstant.appspAppKey);
        AppSpPushLog.d(" AppSpPushConstant.appspSecretKey " + AppSpPushConstant.appspSecretKey);
        AppSpPushLog.d(" AppSpPushConstant.oppoAppKey " + AppSpPushConstant.oppoAppKey);
        AppSpPushLog.d(" AppSpPushConstant.oppoAppSecret " + AppSpPushConstant.oppoAppSecret);
        AppSpPushLog.d(" AppSpPushConstant.xmAppId " + AppSpPushConstant.xmAppId);
        AppSpPushLog.d(" AppSpPushConstant.xmAppKey " + AppSpPushConstant.xmAppKey);
    }

    /**
     * @param appInfo
     * @param key     在manifest文件配置meta的key
     * @return
     */
    private String getMetaInfoByKey(ApplicationInfo appInfo, String key) {
        Object value = appInfo.metaData.get(key);
        String valueStr = "";
        if (value != null) {
            valueStr = value.toString().trim();
        }
        return valueStr;
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        if (call.method.equals("initJpush")) {
            result.success("initJpush " + android.os.Build.VERSION.RELEASE);
        } else if (call.method.equals("getDeviceId")) {
            String locaDeviceId = PhoneUtil.getDeviceId(mContext);
            result.success(locaDeviceId);
        } else {
            result.notImplemented();
        }
    }

    /**
     * @param result 返回的消息
     *               通过invokeMethod的方式，flutter端可不断处理点击消息事件
     */
    private void onMessageClicked(Object result) {
        if (null == result) {
            return;
        }
        channel.invokeMethod("onMessageClicked", result.toString());
    }

    /**
     * @param result 返回的消息
     *               通过invokeMethod的方式，flutter端可不断监听消息内容
     */
    private void onMessageArrived(Object result) {
        if (null == result) {
            return;
        }
        channel.invokeMethod("onMessageArrived", result.toString());
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
        binding.getApplicationContext().unregisterReceiver(mMessageReceiver);
    }

    //获取设备型号
    private int getBrandType() {
        BrandUtil brandUtil = BrandUtil.getInstance(mContext);
        boolean isHuawei = brandUtil.isHuawei();
        boolean isXiaomi = brandUtil.isXiaomi();
        boolean isOppo = brandUtil.isOPPO();
        boolean isVivo = brandUtil.isVIVO();
        if (isHuawei) {
            return BrandType.HUAWEI;
        } else if (isXiaomi) {
            return BrandType.XIAOMI;
        } else if (isOppo) {
            return BrandType.OPPO;
        } else if (isVivo) {
            return BrandType.VIVO;
        } else {
            return BrandType.OTHER;
        }
    }

    private class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            AppSpPushLog.d(" MessageReceiver onReceive ");
            Bundle bundle = intent.getExtras();
            if (bundle == null) {
                return;
            }
            notificationMessageModel = (NotificationMessageModel) bundle.getSerializable(AppSpPushConstant.HNOTIFICATIONMESSAGE);
            int messageType = notificationMessageModel.getMessageType();
            //设备类型
            int brandType = getBrandType();
            //点击或者不处理
            int actionType = notificationMessageModel.getActionType();
            notificationMessageModel.setBrandType(brandType);
            ///处理小米通知，点击通知时
            if (brandType == BrandType.XIAOMI) {
                if (AppSpPushConstant.MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    //如果是点击的通知栏消息，默认是跳转到主页
                    if (actionType == ActionType.CLICK) {
                        AppSpPushLog.d(" MessageReceiver Xiaomi Message Click ");
                        snapToMainActivity();
                    } else {
                        //不点击，把消息传给flutter端，由flutter处理即可
                        String jsonStr = new Gson().toJson(notificationMessageModel);
                        onMessageArrived(jsonStr);
                    }
                }
            } else if (AppSpPushConstant.MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String jsonStr = new Gson().toJson(notificationMessageModel);
                AppSpPushLog.d(" MessageReceiver message jsonStr " + jsonStr);
                if (actionType == ActionType.CLICK) {
                    onMessageClicked(jsonStr);
                } else {
                    onMessageArrived(jsonStr);
                }
            }
        }
    }
}
